import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    //所有任务列表
    list:[],
    //文本框value
    value:'aaa',
    nextId:5,
    viewKey:'all'

  },
  mutations: {
    initList(state,list)
    {
        state.list=list;
    },

    setInputValue(state,value)
    {
      state.value=value
    },
    //添加
    addListItem(state)
    {
      const obj ={
        id:state.nextId,
        info:state.value.trim(),
        done:false
      }
      state.list.push(obj);
      state.nextId++
      state.value=''
    },
    //删除
    delteListItem(state,id)
    {
      state.list.splice(state.list.findIndex(item=>{
        item.id==id
      }),1)    
    },
    //是否选择
    itemChanged(state,obj)
    {

        let index =state.list.findIndex(item=>item.id === obj.id)
      

        state.list[index].done=obj.checked 
    },
    //清除已完成
    clearChecked(state)
    {
      state.list = state.list.filter(item=> item.done===false)
    },
    //点击了不同的页签
    changeViewKey(state,key)
    {
      state.viewKey=key;
    }
  },
  actions: {
    getList(context)
    {
        axios.get('/list.json').then(data=>
          {
              context.commit('initList',data.data)
          })
    }
  },
  getters:{
    //统计未完成任务条数
    unDoneLength(state){
       return state.list.filter(item=> item.done === false).length
    },
    
    infolist(state)
    {
      if(state.viewKey=="all")
      {
        return state.list
      }
      if(state.viewKey=="undone")
      {
        return state.list.filter(item=> !item.done)
      }
      if(state.viewKey=="done")
      {
        return state.list.filter(item=> item.done)
      }
      return state.list
    }
    
   
  },
  modules: {
  }
})
